/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import controller.Action;
import core.App;
import model.Usuario;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;
import validation.CPFValidator;
import validation.RequiredValidator;
import validation.ValidatorManager;

/**
 *
 * @author Daniel
 */
public class salvarUsuario implements Action {

    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String login = request.getParameter("login");
        String senha = request.getParameter("senha");

        ValidatorManager validatorManager = new ValidatorManager();
        validatorManager.addValidator(new RequiredValidator("login", login));
        validatorManager.addValidator(new CPFValidator("senha", senha));

        List<String> erros = validatorManager.validateAll();
        if (erros.isEmpty()) {
            
                    
            try {
                Usuario usuario = new Usuario(login, senha);
                Session session = App.getInstance().getSession();
                Transaction transaction = session.beginTransaction();
                session.save(usuario);
                transaction.commit();
                App.getInstance().addMessage("Usuário salvo com sucesso");
            } catch (Exception e) {
                App.getInstance().addError("Erro a salvar usuario: " + e.getMessage());
            }
            
            
            
        } else {
             App.getInstance().addError("Campo login/senha não pode ser nulo");
        }
        
        List<Usuario> usuarios = App.getInstance().getSession().createQuery("from Usuario").list();
        App.getInstance().setAttribute("usuarios", usuarios);

        
        response.sendRedirect("usuario.jsp");
        
    }
}
